package com.mohe.shanpao.controller.crawler;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mohe.shanpao.controller.BaseController;
import com.mohe.shanpao.domain.crawler.CrawlClue;
import com.mohe.shanpao.domain.crawler.CrawlRule;
import com.mohe.shanpao.service.crawler.CrawlClueService;
import com.mohe.shanpao.service.crawler.CrawlRuleService;
import com.mohe.shanpao.utils.CommonResult;
import com.mohe.shanpao.utils.Constants;

@Controller
@RequestMapping("/crawl")
public class CrawlRuleController extends BaseController{
	
	@Autowired
	private CrawlRuleService crawlRuleService;
	
	@Autowired
	private CrawlClueService crawlClueService;
	
	/**
     * 新增或修改采集规则
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("/ruleUpdate")
    @ResponseBody
    public Object ruleUpdate(HttpServletRequest request)
    {
    	try {
			request.setCharacterEncoding(Constants.DEFAULT_ENCODING);
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage());
		}
    	
    	String ruleId = request.getParameter("p_rule_id");
    	String item = request.getParameter("p_item");
		String name = request.getParameter("p_name");
		String urlRegex = request.getParameter("p_url_regex");
		String listPageRule = StringUtils.isEmpty(request.getParameter("p_page_rule")) ? null : request.getParameter("p_page_rule");
		String nextPageRule = StringUtils.isEmpty(request.getParameter("p_next_rule")) ? null : request.getParameter("p_next_rule");
        
		CommonResult returnObj = new CommonResult();
		
		try
        {
			if(StringUtils.isEmpty(item))
			{
				returnObj.setSuccess(false);
				returnObj.setMessage("item is null . error !");
			}
			else
			{
				CrawlRule record = new CrawlRule();
				record.setItem(item);
				record.setName(name);
				record.setUrlRegex(urlRegex);
				record.setPageRule(listPageRule);
				record.setNextRule(nextPageRule);
				
				if(StringUtils.isEmpty(ruleId))
				{
					int result = crawlRuleService.insert(record);
					if(result > 0)
					{
						returnObj.setSuccess(true);
						returnObj.setMessage("insert rule success");
						
						logger.info("insert rule success . result = "+result);
					}
					else
					{
						returnObj.setSuccess(false);
						returnObj.setMessage("insert rule fail");
						
						logger.warn("insert rule fail . result = "+result);
					}
				}
				else
				{
					long id = Long.parseLong(ruleId);
					if(id > 0)
					{
						record.setId(id);
						int result = crawlRuleService.updateByPrimaryKey(record);
						
						if(result > 0)
						{
							returnObj.setSuccess(true);
							returnObj.setMessage("update rule success");
							
							logger.info("update rule success . rule_id = "+id);
						}
						else
						{
							returnObj.setSuccess(false);
							returnObj.setMessage("update rule fail");
							
							logger.warn("update rule fail . . rule_id = "+id);
						}
					}
				}
			}
        }
        catch (Exception e)
        {
        	returnObj.setMessage(e.getMessage());
        	
            logger.error(e.getMessage());
        }
        
        return returnObj;
    }
    
    /**
     * 新增或修改采集规则
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("/ruleQuery")
    @ResponseBody
    public Object ruleQuery(HttpServletRequest request)
    {
    	try {
			request.setCharacterEncoding(Constants.DEFAULT_ENCODING);
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage());
		}
    	
    	String item = request.getParameter("p_item");
		CommonResult returnObj = new CommonResult();
		
		try
        {
			if(StringUtils.isEmpty(item))
			{
				returnObj.setSuccess(false);
				returnObj.setMessage("item is null . error !");
			}
			else
			{
				CrawlRule rule = crawlRuleService.getCrawlRuleByItem(item);
				
				returnObj.setSuccess(true);
				returnObj.setMessage("get item success . ");
				returnObj.setData(rule);
			}
        }
        catch (Exception e)
        {
        	returnObj.setMessage(e.getMessage());
        	
            logger.error(e.getMessage());
        }
        
        return returnObj;
    }
    
    /**
     * 获取采集线索
     * @return
     * @see [类、类#方法、类#成员]
     */
    @RequestMapping("/clueGet")
    @ResponseBody
    public Object clueGet(HttpServletRequest request)
    {
    	try {
			request.setCharacterEncoding(Constants.DEFAULT_ENCODING);
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage());
		}
    	
		CommonResult returnObj = new CommonResult();
		
		try
        {
			List<CrawlClue> crawlClues = crawlClueService.listCrawlClues();
			
			returnObj.setSuccess(true);
			returnObj.setMessage("get item success . ");
			returnObj.setData(crawlClues.get(0));
			
        }
        catch (Exception e)
        {
        	returnObj.setMessage(e.getMessage());
        	
            logger.error(e.getMessage());
        }
        
        return returnObj;
    }
}
